var city_group_info = new Array();
var busi_type_arr = new Array();
var params = {};
$(function () {
    /* var json = {
     data:12345678901234567
     }
     alert(json.data);*/

    //初始化地市/区县下拉列表
    initCityInfo();


});


var close_btn = function(){
    var jump_url = "opportunity_list.html";
    if(getParams() && getParams()!=""){
        jump_url +="?"+getParams();
    }
    window.location.href=jump_url;
}

var submit_data = function () {

    var result = buildParams();
    if (!result || result == "") {
        return false;
    }
    $("#submit").html("<i class='am-icon-spinner am-icon-spin'></i>&nbsp&nbsp&nbsp&nbsp提交中……");
    if (!$("#submit").hasClass("am-disabled")) {
        $("#submit").addClass("am-disabled");
    }
    var reqUrl = Constants.rpcCrmHost + "StartPreDeal";
    $.ajax({
        type: "post",
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(result),
        url: reqUrl,
        dataType: "text",
        async: true,
        headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
            data=data.replace(/\"PRE_BUSI_ID\":\s*([0-9]+)/,function(a,b){return  '"PRE_BUSI_ID":"'+b+'"';});
            data= $.parseJSON(data);
            if (data.ROOT.RETURN_CODE == "0") {
                params.PRE_BUSI_ID = data.ROOT.OUT_DATA.PRE_BUSI_ID;
                saveDzgData(params);
                addSucc(data.ROOT.RETURN_MSG);
            } else {
                alert(data.ROOT.RETURN_MSG);
                $("#submit").html("提交");
                if ($("#submit").hasClass("am-disabled")) {
                    $("#submit").removeClass("am-disabled");
                }
                console.log("提交数据到RPC接口失败！code:" + data.ROOT.RETURN_MSG);
            }
        },
        error: function (textStatus) {
            $("#submit").html("提交");
            if ($("#submit").hasClass("am-disabled")) {
                $("#submit").removeClass("am-disabled");
            }
            alert("提交数据到RPC接口失败！");
            console.log("提交数据到RPC接口失败！code:" + data.ROOT.RETURN_MSG);
        }
    });
}


/**
 * 保存数据到大掌柜后台
 * @param parameters
 */
var saveDzgData = function (parameters) {
    $.ajax({
        type: "post",
        data: parameters,
        url: "../../../opportunityH5/saveOpportunity",
        dataType: "json",
        async: false,
        headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }

        }
    });
};


var cityChange = function (countyList) {
    var county = $("#opp_city").val().split("#%#")[0];
    var city_obj = null;
    for (var i = 0; i < city_group_info.length; i++) {
        if (city_group_info[i].CITY_GROUP_ID == county) {
            city_obj = city_group_info[i];
            break;
        }
    }
    var county_group_list = city_obj.COUNTY_GROUP_LIST;
    var $tpl = $('#opp_county_data_tpl');
    var source = $tpl.text();
    var template = Handlebars.compile(source);
    var html = template(county_group_list);
    $("#opp_county").html(html);
}

var busiChange = function () {
    var code = $("#opp_bus_big").val().split("#%#")[0];
    var busi_obj = null;
    for (var i = 0; i < busi_type_arr.length; i++) {
        if (busi_type_arr[i].BUSI_TYPE_CODE == code) {
            busi_obj = busi_type_arr[i];
            break;
        }
    }
    var busi_class_list = busi_obj.BUSI_CLASS_LIST;
    var $tpl = $('#opp_bus_sm_tpl');
    var source = $tpl.text();
    var template = Handlebars.compile(source);
    var html = template(busi_class_list);
    $("#opp_bus_sm").html(html);
}

var initCityInfo = function () {
    var params = {
        "BODY": {
            "REQUEST_INFO": {
                "DICT_TYPE": "01"
            }
        }
    }
    var data = JSON.stringify(params);
    $.ajax({
        type: "post",
        contentType: 'application/json; charset=UTF-8',
        data: data,
        url: Constants.rpcCrmHost + "SyncPreDealDict",
        dataType: "json",
        async: true,
        headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
            if (data.ROOT.RETURN_CODE == 0 && data.ROOT.RETURN_MSG == 'ok') {
                var out_data = data.ROOT.OUT_DATA;
                var city_group_list = out_data.CITY_GROUP_LIST;
                var $tpl = $('#opp_city_data_tpl');
                var source = $tpl.text();
                var template = Handlebars.compile(source);
                var html = template(city_group_list);
                city_group_info = city_group_list.CITY_GROUP_INFO;
                $("#opp_city").html(html);
            } else {
                alert("获取地市数据失败！" + data.ROOT.RETURN_MSG);
            }
            init_busi_type();

        },
        error: function (textStatus) {
            alert("获取地市数据失败！服务器没有返回。");
            init_busi_type();
        }
    });

};

var init_busi_type = function () {
    var params = {
        "BODY": {
            "REQUEST_INFO": {
                "DICT_TYPE": "02"
            }
        }
    }
    var data = JSON.stringify(params);
    $.ajax({
        type: "post",
        contentType: 'application/json; charset=UTF-8',
        data: data,
        url: Constants.rpcCrmHost + "SyncPreDealDict",
        dataType: "json",
        async: true,
        headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
            if (data.ROOT.RETURN_CODE == 0 && data.ROOT.RETURN_MSG == 'ok') {
                var OUT_DATA = data.ROOT.OUT_DATA;
                var BUSI_TYPE_LIST = OUT_DATA.BUSI_TYPE_LIST;
                var BUSI_TYPE_LIST_ARR = objToArr(BUSI_TYPE_LIST.BUSI_TYPE);
                BUSI_TYPE_LIST.BUSI_TYPE = BUSI_TYPE_LIST_ARR;
                var $tpl = $('#opp_bus_big_tpl');
                var source = $tpl.text();
                var template = Handlebars.compile(source);
                var html = template(BUSI_TYPE_LIST);
                busi_type_arr = BUSI_TYPE_LIST.BUSI_TYPE;
                $("#opp_bus_big").html(html);
            } else {
                alert("获取类型数据失败！" + data.ROOT.RETURN_MSG);
            }
            init_date_type();
        },
        error: function (textStatus) {
            alert("获取类型数据失败！服务器没有返回。");
            init_date_type();
        }
    });
};

var init_date_type = function () {
    var params = {
        "BODY": {
            "REQUEST_INFO": {
                "DICT_TYPE": "03"
            }
        }
    }
    var data = JSON.stringify(params);
    $.ajax({
        type: "post",
        contentType: 'application/json; charset=UTF-8',
        data: data,
        url: Constants.rpcCrmHost + "SyncPreDealDict",
        dataType: "json",
        async: true,
        headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
            if (data.ROOT.RETURN_CODE == 0 && data.ROOT.RETURN_MSG == 'ok') {
                var OUT_DATA = data.ROOT.OUT_DATA;
                OUT_DATA.CALL_DAY_LIST.CALL_DAY_INFO = objToArr(OUT_DATA.CALL_DAY_LIST.CALL_DAY_INFO);
                var $tpl = $('#opp_date_tpl');
                var source = $tpl.text();
                var template = Handlebars.compile(source);
                var html = template(OUT_DATA.CALL_DAY_LIST);
                $("#opp_date").html(html);
            } else {
                alert("获取回访日期数据失败！" + data.ROOT.RETURN_MSG);
            }
            init_time_type();
        },
        error: function (textStatus) {
            alert("获取回访日期数据失败！服务器没有返回。");
            init_time_type();
        }
    });
};

var init_time_type = function () {
    var params = {
        "BODY": {
            "REQUEST_INFO": {
                "DICT_TYPE": "04"
            }
        }
    }
    var data = JSON.stringify(params);
    $.ajax({
        type: "post",
        contentType: 'application/json; charset=UTF-8',
        data: data,
        url: Constants.rpcCrmHost + "SyncPreDealDict",
        dataType: "json",
        async: true,
        headers: {
      'token': getParamValue('token'),
      'saleType': getParamValue('saleType')
    },
    success: function(data) {
      if (data.ResultCode === 1009) {
        alert('登陆超时，请重新登录！');
        jumpToSignin();
        return;
      }
            if (data.ROOT.RETURN_CODE == 0 && data.ROOT.RETURN_MSG == 'ok') {
                var OUT_DATA = data.ROOT.OUT_DATA;
                OUT_DATA.CALL_TIME_LIST.CALL_TIME_INFO = objToArr(OUT_DATA.CALL_TIME_LIST.CALL_TIME_INFO);
                var $tpl = $('#opp_time_tpl');
                var source = $tpl.text();
                var template = Handlebars.compile(source);
                var html = template(OUT_DATA.CALL_TIME_LIST);
                $("#opp_time").html(html);
            } else {
                alert("获取回访时间数据失败！" + data.ROOT.RETURN_MSG);
            }
        },
        error: function (textStatus) {
            alert("获取回访时间数据失败！服务器没有返回。");
        }
    });
};


var addSucc = function (data) {
    alert("添加成功");
    $("#submit").html("提交");
    if ($("#submit").hasClass("am-disabled")) {
        $("#submit").removeClass("am-disabled");
    }
    var jump_url = "opportunity_list.html";
    if(getParams() && getParams()!=""){
        jump_url +="?"+getParams();
    }
    window.location.href=jump_url;
};

var buildParams = function () {

    //预受理名称
    if ($("#opp_name").val().trim() != "") {
        params.PRE_BUSI_NAME = $("#opp_name").val().trim();
    } else {
        alert("预受理名称不能为空");
        return false;
    }
    //集团名称
    if ($("#group_name").val().trim() != "") {
        params.CUST_GRP_NAME = $("#group_name").val().trim();
    } else {
        alert("集团名称不能为空");
        return false;
    }

    //集团联系人
    if ($("#link_man").val().trim() != "") {
        params.CUST_CONT_NAME = $("#link_man").val().trim();
    } else {
        alert("联系人不能为空");
        return false;
    }

    //联系电话
    if ($("#link_mobile_phone").val().trim() != "") {
        var mobile_phone = $("#link_mobile_phone").val().trim();
        if (!(/^1[3|4|5|7|8]\d{9}$/.test(mobile_phone))) {
            alert("对不起，您输入的手机号码格式不正确!");
            return false;
        }
        params.CUST_CONT_PHONE = mobile_phone;
    } else {
        alert("联系电话不能为空");
        return false;
    }
    //联系固话，可以为空
    if ($("#link_phone").val().trim() != "") {
        if (!(/^0\d{2,3}-?\d{7,8}$/.test($("#link_phone").val().trim()))) {
            alert("对不起，您输入的电话号码格式不正确!");
            return false;
        }
        params.CUST_CONT_TEL = $("#link_phone").val();
    }


    if ($("#address").val().trim() != "") {
        params.CUST_CONT_ADDR = $("#address").val().trim();
    } else {
        alert("联系地址不能为空");
        return false;
    }

    //归属地市ID
    if ($("#opp_city").val() != "") {
        params.CITY_GROUP_ID = $("#opp_city").val().split("#%#")[0];
    } else {
        alert("归属地市不能为空");
        return false;
    }
    //归属地市名称
    if ($("#opp_city").val() != "") {
        params.CITY_GROUP_NAME = $("#opp_city").val().split("#%#")[1];
    } else {
        alert("归属地市不能为空");
        return false;
    }

    //归属区县
    if ($("#opp_county").val() != "") {
        params.COUNTY_GROUP_ID = $("#opp_county").val().split("#%#")[0];
    } else {
        alert("归属区县不能为空");
        return false;
    }
    //归属区县
    if ($("#opp_county").val() != "") {
        params.COUNTY_GROUP_NAME = $("#opp_county").val().split("#%#")[1];
    } else {
        alert("归属区县不能为空");
        return false;
    }


    //业务大类
    if ($("#opp_bus_big").val() != "") {
        var BUSI_TYPE_ARR = $("#opp_bus_big").val().split("#%#");
        params.BUSI_TYPE = BUSI_TYPE_ARR[0];
        params.BUSI_TYPE_NAME = BUSI_TYPE_ARR[1];
    } else {
        alert("业务大类不能为空");
        return false;
    }
    //业务小类
    if ($("#opp_bus_sm").val() != "") {
        var BUSI_CLASS_ARR = $("#opp_bus_sm").val().split("#%#");
        params.BUSI_CLASS = BUSI_CLASS_ARR[0];
        params.BUSI_CLASS_NAME = BUSI_CLASS_ARR[1];
    } else {
        alert("业务小类不能为空");
        return false;
    }
    //需求描述
    if ($("#describe").val().trim() != "") {
        params.BUSI_REQ_DESC = $("#describe").val().trim();
    } else {
        alert("需求描述不能为空");
        return false;
    }
    //预约回访日期
    if ($("#opp_date").val() != "-1") {
        params.PRE_CALL_DAY = $("#opp_date").val();
    } else {
        alert("请选择预约回访日期");
        return false;
    }
    //预约回访时间
    if ($("#opp_time").val() != "-1") {
        params.PRE_CALL_TIME = $("#opp_time").val();
    } else {
        alert("请选择预约回访时间");
        return false;
    }

    //渠道来源
    if ($("#opp_source").val() != "-1") {
        params.CHAN_ID = $("#opp_source").val();
    } else {
        alert("请选择渠道来源");
        return false;
    }
    //预受理时限
    if ($("#time_over").val() != "") {

        if (!(/^[0-9]*[1-9][0-9]*$/.test($("#time_over").val().trim()))) {
            alert("对不起，您输入的预受理时限格式不正确!");
            return false;
        }
        params.CALL_LIMIT_DAY = $("#time_over").val();
    } else {
        alert("预受理时限不能为空");
        return false;
    }
    //备注
    params.REMARK = $("#remark").val();
    //操作
    params.opperet = $("#opperet").val();
    //批注
    params.pizhu = $("#pizhu").val();
    //下一步受理环节
    params.next_segment = $("#next_segment").val();
    var result = {
        "BODY": {
            "REQUEST_INFO": params
        }
    };
    return result;
};

